package ui.prototypes;

import android.app.Fragment;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class CashFlowFragment extends Fragment {

    /*
     * Stores the current year
     */
    private int mCurrentYear;

    /*
     * Stores the current month
     */
    private int mCurrentMonth;

    /*
     * ListView used to display cash flow
     */
    private ListView mListView;

    public CashFlowFragment() {

    }

    public void setDate(int year, int month) {
        mCurrentYear = year;
        mCurrentMonth = month;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.cash_flow, container, false);

        mListView = (ListView) view.findViewById(R.id.cash_flow_list);

        ContentResolver resolver = getActivity().getContentResolver();

        Cursor cursor = resolver.query(CashFlowContract.CashFlowTable.CONTENT_URI,
                null, null, null, null);

        cursor.setNotificationUri(getActivity().getContentResolver(), CashFlowContract.CashFlowTable.CONTENT_URI);

        CashFlowCursorAdapter adapter = new CashFlowCursorAdapter(getActivity(), cursor);
        mListView.setAdapter(adapter);

        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                CashFlow cf = (CashFlow) view.getTag();
                openFlowEditor(cf);
            }
        });

        return view;
    }

    public void openFlowEditor(CashFlow cf) {
        Intent intent = new Intent(getActivity(), CashFlowItemEditorActivity.class);

        if(cf != null) {
            intent.putExtra("cash_flow", cf);
        }

        startActivity(intent);
    }

}
